package com.corpgovernment.organization.controller.invoice;

import com.corpgovernment.api.organization.model.commonInvoice.CommonInvoiceVo;
import com.corpgovernment.api.organization.model.commonInvoice.request.InvoiceListAllTypeRequest;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.ExceptionCodeEnum;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.entity.db.MbCommonInvoiceInfo;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.organization.service.impl.CommonInvoiceInfoService;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: CommonInvoiceInfoController
 * @author: ezchen
 * @date: Created in 10:44 2019/8/13
 * @Version: 1.0
 **/
@RestController
@RequestMapping("/commonInvoiceInfo")
public class CommonInvoiceInfoController {

    @Autowired
    private CommonInvoiceInfoService commonInvoiceInfoService;
    @Autowired
    private IOrganizationInfoService organizationInfoService;


    /**
     * 获取常用发票列表
     * @param request
     * @return
     */
//    @RequestMapping(value = "/get",method = {RequestMethod.GET,RequestMethod.POST})
//    public JSONResult getCommonInvoiceInfo(@RequestBody InvoiceListAllTypeRequest request, @RequestParam String uId){
//        request.setUid(uId);
//        return JSONResult.success(commonInvoiceInfoService.listByPage(request));
//    }

    /**
     * 获取上次使用的发票信息
     *
     * @return
     */
    @RequestMapping(value = "/getDefault", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONResult<CommonInvoiceVo> getDefaultCommonInvoiceInfo(@RequestParam String uId, @RequestParam String orgId) {
        MbCommonInvoiceInfo dbInfo = commonInvoiceInfoService.getDefaultCommonInvoiceInfo(uId, orgId);
        if (dbInfo == null) {
            //无发票信息时设置默认值
            CommonInvoiceVo vo = new CommonInvoiceVo();
            vo.setInvoiceType(1);
            vo.setInvoiceTitleType(1);
            return JSONResult.success(vo);
        } else {
            CommonInvoiceVo vo = new CommonInvoiceVo();
            vo.setId(dbInfo.getId());
            vo.setInvoiceTitleType(dbInfo.getInvoiceType());
            if (1 == dbInfo.getInvoiceTaxType()) {
                vo.setInvoiceType(1);
            } else {
                vo.setInvoiceType(2);
            }
            vo.setAccountBank(dbInfo.getAccountBank());
            vo.setAccountCardNo(dbInfo.getAccountCardNo());
            vo.setCorporationAddress(dbInfo.getCorporationAddress());
            vo.setCorporationTel(dbInfo.getCorporationPhone());
            vo.setInvoiceTitle(dbInfo.getInvoiceTitle());
            vo.setTaxpayerNumber(dbInfo.getTaxId());
            return JSONResult.success(vo);
        }
    }

    /**
     * 公司获取常用发票列表
     * @param mbCommonInvoiceInfoRequestVo
     * @return
     */
//    @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
//    public JSONResult list( @RequestBody MbCommonInvoiceInfoRequestVo mbCommonInvoiceInfoRequestVo){
//        mbCommonInvoiceInfoRequestVo.setType(1);
//        return JSONResult.success(commonInvoiceInfoService.listByPage(mbCommonInvoiceInfoRequestVo));
//    }

    /**
     * 获取常用发票列表(app pcbook )
     *
     * @param userInfo
     * @param request
     * @return
     */
    @RequestMapping(value = "/invoiceListAllType")
    public JSONResult invoiceListAllType(BaseUserInfo userInfo, @RequestBody InvoiceListAllTypeRequest request) {
        request.setUid(userInfo.getUid());
        request.setOrgId(userInfo.getOrgId());
        request.setCorpId(userInfo.getCorpId());
        return JSONResult.success(commonInvoiceInfoService.listByPage(request));
    }
    /*    *//**
     * 获取上次使用的发票信息
     * @return
     *//*
    @RequestMapping(value = "/getDefault",method = {RequestMethod.GET,RequestMethod.POST})
    public JSONResult<CommonInvoiceVo> getDefaultCommonInvoiceInfo(@RequestParam String uid){
        MbCommonInvoiceInfo dbInfo=commonInvoiceInfoService.getDefaultCommonInvoiceInfo(uid);
        if (dbInfo==null){
            //无发票信息时设置默认值
            CommonInvoiceVo add=new CommonInvoiceVo();
            add.setInvoiceType(1);
            add.setInvoiceTitleType(1);
            return JSONResult.success(add);
        }else {
            CommonInvoiceVo add=new CommonInvoiceVo();
            add.setId(dbInfo.getId());
            add.setAccountBank(dbInfo.getAccountBank());
            add.setAccountCardNo(dbInfo.getAccountCardNo());
            add.setCorporationAddress(dbInfo.getCorporationAddress());
            add.setCorporationTel(dbInfo.getCorporationPhone());
            add.setInvoiceTitle(dbInfo.getInvoiceTitle());
            add.setTaxpayerNumber(dbInfo.getTaxId());
            return JSONResult.success(add);
        }
    }*/

    /**
     * 公司添加常用发票(废弃，现在是编辑组织信息的时候一同添加/编辑发票，而不是单独的)
     * @param mbCommonInvoiceInfo
     * @return
     */
//    @PostMapping(value = "/add")
//    public JSONResult addCommonInvoiceInfo(@RequestBody MbCommonInvoiceInfo mbCommonInvoiceInfo){
//        checkCommonInvoiceInfoVo(mbCommonInvoiceInfo);
//        mbCommonInvoiceInfo.setId(null);
//        mbCommonInvoiceInfo.setIsDeleted(false);
//        mbCommonInvoiceInfo.setInvoiceType(1);
//        return JSONResult.success(commonInvoiceInfoService.addCommonInvoiceInfo(mbCommonInvoiceInfo));
//    }

    /**
     * 公司修改常用发票(废弃，现在是编辑组织信息的时候一同添加/编辑发票，而不是单独的)
     * @param mbCommonInvoiceInfo
     * @return
     */
//    @PostMapping(value = "/update")
//    public JSONResult updateCommonInvoiceInfo(@RequestBody MbCommonInvoiceInfo mbCommonInvoiceInfo){
//        checkCommonInvoiceInfoVo(mbCommonInvoiceInfo);
//        mbCommonInvoiceInfo.setIsDeleted(false);
//        mbCommonInvoiceInfo.setInvoiceType(1);
//        return JSONResult.success(commonInvoiceInfoService.updateCommonInvoiceInfo(mbCommonInvoiceInfo));
//    }


    /**
     * 公司删除常用发票（参数里边只有id）(废弃，现在是编辑组织信息的时候一同添加/编辑发票，而不是单独的)
     * @param mbCommonInvoiceInfo
     * @return
     */
//    @PostMapping(value = "/delete")
//    public JSONResult deleteCommonInvoiceInfo(@RequestParam MbCommonInvoiceInfo mbCommonInvoiceInfo){
//        mbCommonInvoiceInfo.setInvoiceType(1);
//        commonInvoiceInfoService.deleteCommonInvoiceInfo(mbCommonInvoiceInfo);
//        return JSONResult.success(null);
//    }

    /**
     * 个人添加常用发票
     *
     * @param mbCommonInvoiceInfo
     * @return
     */
    @PostMapping(value = "/addBySelf")
    public JSONResult addCommonInvoiceBySelf(BaseUserInfo userInfo, @RequestBody MbCommonInvoiceInfo mbCommonInvoiceInfo) {
        checkCommonInvoiceInfoVo(mbCommonInvoiceInfo);
        mbCommonInvoiceInfo.setIsDeleted(false);
        mbCommonInvoiceInfo.setOrgId(userInfo.getOrgId());
        mbCommonInvoiceInfo.setUid(userInfo.getUid());
        commonInvoiceInfoService.addCommonInvoiceInfo(mbCommonInvoiceInfo);
        return JSONResult.success(null);
    }

    /**
     * 个人修改常用发票
     *
     * @param mbCommonInvoiceInfo
     * @return
     */
    @PostMapping(value = "/updateBySelf")
    public JSONResult updateCommonInvoiceBySelf(BaseUserInfo baseUserInfo, @RequestBody MbCommonInvoiceInfo mbCommonInvoiceInfo) {
        checkCommonInvoiceInfoVo(mbCommonInvoiceInfo);
        commonInvoiceInfoService.updateCommonInvoiceInfo(mbCommonInvoiceInfo);
        return JSONResult.success(null);
    }


    /**
     * 个人删除常用发票(参数里边只有id）
     *
     * @param mbCommonInvoiceInfo
     * @return
     */
    @PostMapping(value = "/deleteBySelf")
    public JSONResult deleteCommonInvoiceBySelf(BaseUserInfo baseUserInfo, @RequestBody MbCommonInvoiceInfo mbCommonInvoiceInfo) {
        mbCommonInvoiceInfo.setUid(baseUserInfo.getUid());
        mbCommonInvoiceInfo.setOrgId(baseUserInfo.getOrgId());
        commonInvoiceInfoService.deleteCommonInvoiceInfo(mbCommonInvoiceInfo);
        return JSONResult.success(null);
    }


    /**
     * 公司根据组织结构id查询发票信息
     *
     * @param mbCommonInvoiceInfo
     * @return
     */
    @PostMapping(value = "/listByOrgId")
    public JSONResult<List<MbCommonInvoiceInfo>> listByOrgId(@RequestBody MbCommonInvoiceInfo mbCommonInvoiceInfo) {

        if (StringUtils.isBlank(mbCommonInvoiceInfo.getOrgId())) {
            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "组织信息为空！");
        }
        String orgId = mbCommonInvoiceInfo.getOrgId();

        MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(orgId);
        if (mbOrgInfo != null && OrgTypeEnum.C.getCode().equals(mbOrgInfo.getOrgType())) {
            return JSONResult.success(commonInvoiceInfoService.listByOrgIdReal(orgId));
        } else if (mbOrgInfo != null && OrgTypeEnum.D.getCode().equals(mbOrgInfo.getOrgType())) {
            //如果是部门，获取该部门公司
            mbOrgInfo = organizationInfoService.findRecentCompanyIdByOrgId(orgId);
            if (mbOrgInfo != null) {
                return JSONResult.success(commonInvoiceInfoService.listByOrgIdReal(mbOrgInfo.getOrgId()));
            }
        }

        return JSONResult.success(new ArrayList<>());
    }

    private void checkCommonInvoiceInfoVo(MbCommonInvoiceInfo mbCommonInvoiceInfo) {
        if (!StringUtils.isBlank(mbCommonInvoiceInfo.getTaxId())) {
            String regex = "^[a-z0-9A-Z]+$";
            //税号必须为数字或字母，15~20位
            if (!mbCommonInvoiceInfo.getTaxId().matches(regex)) {
                throw new CorpBusinessException(ExceptionCodeEnum.Alert, "税号必须为数字或字母！");
            } else if (mbCommonInvoiceInfo.getTaxId().length() < 15 || mbCommonInvoiceInfo.getTaxId().length() > 20) {
                throw new CorpBusinessException(ExceptionCodeEnum.Alert, "税号必须为15~20位！");
            }
        }
        if (1 == mbCommonInvoiceInfo.getInvoiceTaxType()) {
            if (StringUtils.isBlank(mbCommonInvoiceInfo.getCorporationAddress())) {
                throw new CorpBusinessException(ExceptionCodeEnum.Alert, "增值税专用发票 公司名称必填！");
            }
            if (StringUtils.isBlank(mbCommonInvoiceInfo.getCorporationPhone())) {
                throw new CorpBusinessException(ExceptionCodeEnum.Alert, "增值税专用发票 公司电话必填！");
            }
            if (StringUtils.isBlank(mbCommonInvoiceInfo.getAccountBank())) {
                throw new CorpBusinessException(ExceptionCodeEnum.Alert, "增值税专用发票 银行名称必填！");
            }
            if (StringUtils.isBlank(mbCommonInvoiceInfo.getAccountCardNo())) {
                throw new CorpBusinessException(ExceptionCodeEnum.Alert, "增值税专用发票 银行账号必填！");
            } else if (!isNumeric(mbCommonInvoiceInfo.getAccountCardNo())) {
                throw new CorpBusinessException(ExceptionCodeEnum.Alert, "增值税专用发票 银行账号只能输入数字！");
            }
        }
    }

    private boolean isNumeric(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (Character.isDigit(str.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }
}
